package com.dayuan.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dayuan.bean.UserInfo;
import com.dayuan.constant.AjaxMsg;
import com.dayuan.dedis.Handler;
import com.dayuan.service.OrderService;
import com.dayuan.vo.ResultVo;



@Controller
@RequestMapping("/order")
public class OrderController implements InitializingBean {

	@Resource
	private OrderService orderService;

	@Resource
	private Handler handler;

	/*private static Logger logger = LoggerFactory.getLogger(OrderController.class);*/

	/* 下订单 */
	@RequestMapping(value = "/order.im", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public ResultVo Order(HttpSession session, Integer goodsId, Integer Number) {
		ResultVo resultVo = new ResultVo();

		UserInfo userinfo = (UserInfo) session.getAttribute("userinfo");

		try {
			if (goodsId == null || Number == null) {
				resultVo.setCode(AjaxMsg.FAIL.getValue());
				resultVo.setMsg("网页消失");
				return resultVo;
			}

			String result = orderService.order(goodsId, Number, userinfo.getId());
			if (result == AjaxMsg.PAY_FAIL.getPay()) {
				resultVo.setCode(AjaxMsg.FAIL.getValue());
				resultVo.setMsg("库存不足");
				return resultVo;
			}

			resultVo.setCode(AjaxMsg.SUCCESS.getValue());
			resultVo.setMsg(result);
			System.out.println(result);
			return resultVo;
		} catch (Exception e) {
			e.printStackTrace();
			resultVo.setCode(AjaxMsg.FAIL.getValue());
			resultVo.setMsg("网页消失在异次元");
			return resultVo;
		}

	}


	// 阻塞队列异步通知
	@Override
	public void afterPropertiesSet() throws Exception {
		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				 handler.get();
				
			}
		});
		thread.start();

	}
}
